/* 
 playMusic.js
 用于扫描音乐文件夹，提取音乐元数据和歌词，生成音乐列表文件

*/
import * as fs from 'node:fs'
import * as path from 'node:path'
import { parseBuffer, ILyricsTag } from 'music-metadata'
import { lrcToNetease } from '../utils/lrcToNetease'

// 音乐文件夹路径
// const MUSIC_FOLDER = '../../../resources/localMusic' // 修改为你的音乐文件夹路径

const MUSIC_FOLDER = path.resolve(__dirname, '../../renderer/src/assets/audio') // 修改为你的音乐文件夹路径
const OUTPUT_FILE = path.resolve(__dirname, './musicList.json')

// 支持的音频格式
const AUDIO_EXTENSIONS = new Set(['.mp3', '.flac', '.wav', '.m4a', '.aac', '.ogg', '.wma', '.alac'])
// 支持的歌词格式
const LYRIC_EXTENSIONS = new Set(['.lrc'])
interface LyricLine {
  time: number // 毫秒
  content: ILyricsTag[]
}

// 主函数
async function searchMusic(musicFolder: string, id: string) {
  const METADATA_FILE = `${musicFolder}/metadata.json`
  debugger
  const data = await fs.promises.readFile(METADATA_FILE, 'utf-8')
  const musicList = JSON.parse(data)
  const music = musicList?.results.find((item: any) => item.id === id)
  if (music) {
    const lyricUrl = `${musicFolder}/${music.pathLyrics}`
    // 提取歌词
    let lyric: LyricLine[] = []
    let neteaseLyric: any[] = []
    let lrcText: string = ''

    // 检查是否存在 .lrc 文件
    if (
      await fs.promises
        .access(lyricUrl)
        .then(() => true)
        .catch(() => false)
    ) {
      const lrcContent = await fs.promises.readFile(lyricUrl, 'utf-8')
      // 解析lrc歌词,转换成网易云歌词格式
      neteaseLyric = lrcToNetease(lrcContent)
      // 解析lrc歌词,转换成标准歌词格式
      lyric = parseLrc(lrcContent)
      // 原始歌词字符串
      lrcText = lrcContent

      // lyric.push(...parseLrc(lrcContent))
    }

    return { ...music, lyric, lrcText, neteaseLyric }
  }

  /*  const scanDir = async (dir) => {
    const entries = await fs.promises.readdir(dir, { withFileTypes: true })

    for (const entry of entries) {
      const fullPath = path.join(dir, entry.name)
      // const index = entries.findIndex(entry)

      if (entry.isDirectory()) {
        await scanDir(fullPath) // 递归进入子目录
      } else {
        const ext = path.extname(entry.name).toLowerCase()
        if (AUDIO_EXTENSIONS.has(ext)) {
          try {
            const buffer = await fs.promises.readFile(fullPath)
            const metadata = await parseBuffer(buffer, ext.slice(1)) // 去掉点号传格式，如 'mp3'

            const baseName = path.basename(entry.name, ext)
            const lrcPath = path.join(dir, baseName + '.lrc')
            // 提取歌词
            let lyric: LyricLine[] = []

            // 检查是否存在 .lrc 文件
            if (
              await fs.promises
                .access(lrcPath)
                .then(() => true)
                .catch(() => false)
            ) {
              const lrcContent = await fs.promises.readFile(lrcPath, 'utf-8')
              lyric = parseLrc(lrcContent)

              // lyric.push(...parseLrc(lrcContent))
            } else if (metadata.common.lyrics) {
              // 回退：使用嵌入歌词（无时间轴）
              lyric.push({
                time: 0,
                content: metadata.common.lyrics
              })
            }

            const musicItem = {
              id: path.basename(fullPath, ext), // 使用文件名作为ID
              musicUrl: `file://${path.resolve(fullPath)}`, // 绝对路径 URL
              title: metadata.common.title || path.basename(fullPath, ext),
              artist: metadata.common.artist || 'Unknown Artist',
              album: metadata.common.album || 'Unknown Album',
              genre: metadata.common.genre || [],
              duration: Math.round((metadata.format.duration || 0) * 1000), // 转为毫秒
              bitrate: metadata.format.bitrate || 0,
              sampleRate: metadata.format.sampleRate || 0,
              codec: metadata.format.codec || '',
              cover: {
                coverBuffer: Buffer.from([]),
                base64: '',
                mimeType: '',
                size: 0
              },
              lyric // 填入歌词
            }

            // 处理封面
            if (metadata.common.picture && metadata.common.picture.length > 0) {
              const picture = metadata.common.picture[0]
              musicItem.cover.coverBuffer = Buffer.from(picture.data) // 保持为 Buffer
              musicItem.cover.base64 = `data:${picture.format};base64,${musicItem.cover.coverBuffer.toString('base64')}`
              musicItem.cover.mimeType = picture.format
              musicItem.cover.size = picture.data.length
            }

            // 处理歌词（如果有嵌入歌词）
            if (metadata.common.lyrics) {
              // 简单处理：整段歌词作为一条
              musicItem.lyric = [
                {
                  time: 0,
                  content: metadata.common.lyrics
                }
              ]
            } else if (metadata.common.lyrics) {
              musicItem.lyric = [
                {
                  time: 0,
                  content: metadata.common.lyrics
                }
              ]
            }

            musicList.push(musicItem)
          } catch (err: any) {
            console.warn(`无法读取文件元数据: ${fullPath}`, err.message)
          }
        }
      }
    }
  } */

  /* try {
    // await scanDir(MUSIC_FOLDER)
    // 使用下标作为id
    musicList.map((item: any, index: number) => (item.id = index.toString()))
    // 写入 JSON 文件
    await fs.promises.writeFile(OUTPUT_FILE, JSON.stringify({ musicList }, null, 2), 'utf-8')
    console.log(`✅ 音乐列表已生成: ${path.resolve(OUTPUT_FILE)}`)
    console.log(`📁 共扫描到 ${musicList.length} 首音乐文件。`)
  } catch (err) {
    console.error('❌ 扫描失败:', err)
  } */
}

// 解析 LRC 歌词文件
function parseLrc(content: string): LyricLine[] {
  const lines = content.split(/\r?\n/)
  const lyric: LyricLine[] = []

  const timeRegex = /\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/g

  for (const line of lines) {
    const text: any = line.replace(timeRegex, '').trim()

    if (!text) continue

    /* const matches = [...line.matchAll(timeRegex)] */
    // START 这段代码 === const matches = [...line.matchAll(timeRegex)]
    const matches: RegExpExecArray[] = []
    let match: RegExpExecArray | null

    // 重置正则（避免 lastIndex 影响）
    timeRegex.lastIndex = 0

    while ((match = timeRegex.exec(line)) !== null) {
      matches.push(match)
    }
    // END 这段代码 === const matches = [...line.matchAll(timeRegex)]

    if (matches.length === 0) continue

    for (const match of matches) {
      const [, mm, ss, xx] = match
      const minutes = parseInt(mm, 10)
      const seconds = parseInt(ss, 10)
      const millis = xx ? parseInt(xx.padEnd(3, '0'), 10) : 0
      const time = (minutes * 60 + seconds) * 1000 + millis

      lyric.push({ time, content: text })
    }
  }

  // 按时间排序
  lyric.sort((a, b) => a.time - b.time)
  return lyric
}

export { searchMusic }
